package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseFragmentActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.CmnBookProductionAdapter;
import com.hemaapp.yjnh.adapter.CmnProductionAdapter;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.ClientDetails;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.Img;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.listener.OnBlogItemClickListener;
import com.hemaapp.yjnh.listener.OnItemClickListener;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.utils.LoginUtil;
import com.hemaapp.yjnh.view.ShowTextPop;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;

/**
 * 实物类商家详情
 *
 * @author GuiyouZhang
 *         创建时间：2015年9月16日
 */
public class CmnMerchantDetailActivity extends BaseFragmentActivity implements OnClickListener {

    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_right_img)
    ImageView titleRightImg;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.img_merchant)
    ImageView imgMerchant;
    @Bind(R.id.tv_merchant_name)
    TextView tvMerchantName;
    @Bind(R.id.ratingBar)
    RatingBar ratingBar;
    @Bind(R.id.tv_phone)
    TextView tvPhone;
    @Bind(R.id.tv_consult_online)
    TextView tvConsultOnline;
    @Bind(R.id.tv_attation)
    TextView tvAttation;
    @Bind(R.id.ll_attation)
    LinearLayout llAttation;
    @Bind(R.id.tv_merchant_address)
    TextView tvMerchantAddress;
    @Bind(R.id.line_products)
    View lineProducts;
    @Bind(R.id.line_introduce)
    View lineIntroduce;
    @Bind(R.id.tv_info)
    TextView tvInfo;
    @Bind(R.id.iv_info)
    ImageView ivInfo;
    @Bind(R.id.layout_info)
    LinearLayout layoutInfo;
    @Bind(R.id.listview)
    XtomListView listview;
    @Bind(R.id.scrollview)
    ScrollView scrollview;
    @Bind(R.id.layout_refresh)
    RefreshLoadmoreLayout layoutRefresh;

    private LoginUtil.LoginCallBack loginCallBack;
    private String client_id;//当前商家的id
    private User user;
    private String lat = "";//纬度
    private String lng = "";//经度
    private ClientDetails details;
    private ArrayList<Blog> mBlogs = new ArrayList<>();//商家的商品
    private CmnProductionAdapter mAdapter;
    private CmnBookProductionAdapter mBookAdapter;
    private int curPage = 0;
    private String keytype = "";//商家的类型，
    //1:粮票超值 ；2:有机商品 ；3:田家商品 ；4:地标商品 ；5:村游商品 ；6:唠嗑帖子 ；7:农货日志
    //8:粮库商品 ；9:乐乐商品 ；10:走走相关 ；11:特产商品 ；12:苗木 ；13:花卉 ；14:家电 ；15:日用品
    //16:粮库商家商品    17:农需商品    18:全部商品
    private String keyid;//这里参照api帖子列表: http://124.128.23.74:8008/group8/hm_yjnh/web/Webapi/mvc/?v=3.0.0
//	private String seller_id="";// 卖家id	可选传参数，role=4,5,9,10,11可传

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_merchant_detail);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        lat = XtomSharedPreferencesUtil.get(mContext, "lat");
        lng = XtomSharedPreferencesUtil.get(mContext, "lng");
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void getExras() {
        client_id = mIntent.getStringExtra("client_id");
        String token = user == null ? "" : user.getToken();
        getNetWorker().clientGet(token, client_id);
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void setListener() {
        titleText.setText("商家详情");
        titleRightBtn.setVisibility(View.GONE);
        titleRightImg.setVisibility(View.VISIBLE);
        titleRightImg.setImageResource(R.drawable.heart_while_stroke);
        listview.setFocusable(false);
        layoutRefresh.setOnStartListener(new OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {
                curPage = 0;
                String token = user == null ? "" : user.getToken();
                getNetWorker().clientGet(token, client_id);
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {
                curPage++;
                getGoodsList();
            }
        });
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask.getHttpInformation();
        switch (information) {
            case CLIENT_GET:
            case BLOG_LIST:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CLIENT_GET:
            case BLOG_LIST:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CLIENT_GET:
                HemaArrayResult<ClientDetails> uResult = (HemaArrayResult<ClientDetails>) baseResult;
                details = uResult.getObjects().get(0);
                //0普通用户;1田家用户;2地标商家;3村游商家;4省级代理;5运营商;6乐乐商家;7特产商家;8粮库商家;
                //11走走露营商家;12走走房车商家;21苗木;22花卉;23家电;24日用商品
                transRole(details.getRole());
                getGoodsList();
                setData();
                break;
            case BLOG_LIST:
                String page = netTask.getParams().get("page");
                HemaPageArrayResult<Blog> bResult = (HemaPageArrayResult<Blog>) baseResult;
                if (bResult == null || bResult.getObjects() == null)
                    return;
                if ("0".equals(page)) {// 刷新
                    layoutRefresh.refreshSuccess();
                    mBlogs.clear();
                    mBlogs.addAll(bResult.getObjects());
                } else {
                    layoutRefresh.loadmoreSuccess();
                    if (bResult.getObjects().size() > 0)
                        mBlogs.addAll(bResult.getObjects());
                    else {
                        layoutRefresh.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                refreshData(-1);
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                ShowTextPop stp = new ShowTextPop(mContext,
                        findViewById(R.id.father));
                String follow = details.getFollowflag();
                if (follow.equals("0")) {//关注成功
                    details.setFollowflag("1");
                    stp.setText("已关注");
                    stp.setDrawable(R.drawable.follow, 0, 0, 0);
                    titleRightImg.setImageResource(R.drawable.heart_while);
                } else if (follow.equals("1")) {//取消关注
                    details.setFollowflag("0");
                    stp.setText("取消关注成功");
                    stp.setDrawable(R.drawable.unfollow, 0, 0, 0);
                    titleRightImg.setImageResource(R.drawable.heart_while_stroke);
                }
                stp.show();
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CLIENT_GET:
                showTextDialog("获取商家信息失败！");
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
            case BLOG_LIST:
                XtomToastUtil.showShortToast(mContext, "获取商品失败，" + baseResult.getMsg());
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                String oper = netTask.getParams().get("oper");
                // 操作	1添加 ，2取消 ;3：清空
                if (oper.equals("1")) {
                    showTextDialog("添加关注失败!");
                } else {
                    showTextDialog("取消关注失败!");
                }
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CLIENT_GET:
                showTextDialog("获取商家信息失败！");
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
            case BLOG_LIST:
                XtomToastUtil.showShortToast(mContext, "获取商品失败，请稍后再试");
                refreshData(failedType);
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                String oper = netTask.getParams().get("oper");
                // 操作	1添加 ，2取消 ;3：清空
                if (oper.equals("1")) {
                    showTextDialog("添加关注失败!");
                } else {
                    showTextDialog("取消关注失败!");
                }
                break;
        }
    }

    /**
     * 刷新实物商品
     *
     * @param failedType
     */
    private void refreshData(int failedType) {
        if (mAdapter == null) {
            mAdapter = new CmnProductionAdapter(mContext, mBlogs);
            mAdapter.setItemClickListener(new OnBlogItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    Intent it = new Intent(mContext, CmnProductionDetailActivity.class);
                    it.putExtra("blog_id", mBlogs.get(position).getId());
                    mContext.startActivity(it);
                }

                @Override
                public void onCartListener(int position) {

                }
            });
            mAdapter.setEmptyString("暂无商品");
            listview.setAdapter(mAdapter);
            BaseUtil.setListViewHeightBasedOnChildren(listview, 50, this);
        } else {
            mAdapter.notifyDataSetChanged();
            BaseUtil.setListViewHeightBasedOnChildren(listview, 50, this);
        }
        mAdapter.setFailtype(failedType);
    }

    /**刷新预约类商家
     * @param failedType
     */
    private void refreshBookBlog(int failedType) {
        if (mBookAdapter == null) {
            mBookAdapter = new CmnBookProductionAdapter(mContext, mBlogs);
            mBookAdapter.setEmptyString("暂时没有商品");
            mBookAdapter.setClickListener(new OnItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    Intent it = BaseUtil.createBlogIntent(mContext, mBlogs.get(position).getType());
                    it.putExtra("blog_id", mBlogs.get(position).getId());
                    startActivity(it);
                }
            });
            listview.setAdapter(mBookAdapter);
            BaseUtil.setListViewHeightBasedOnChildren(listview, 50, this);
        } else {
            BaseUtil.setListViewHeightBasedOnChildren(listview, 50, this);
            mBookAdapter.setEmptyString("暂时没有商品");
            mBookAdapter.notifyDataSetChanged();
        }
        mBookAdapter.setFailtype(failedType);
    }

    /**
     * 获取粮库店铺内的商品列表
     */
    private void getGoodsList() {
        getNetWorker().blogList(keytype, keyid, "1", "1", "", "", "", "", "", client_id, lng, lat, "", "", curPage + "");
    }

    private void setData() {
        if (details == null) {
            return;
        }
        tvMerchantName.setText(details.getNickname());
        tvMerchantAddress.setText(details.getAddress());
        tvInfo.setText(details.getContent());
        ImageUtils.loadBigImage(mContext, details.getBackimg(), imgMerchant);
        ImageUtils.loadBigImage(mContext, details.getImgbigurl0(), ivInfo);
        Float score = Float.parseFloat(details.getStarscore());
        ratingBar.setRating(score);
        if (!isNull(details.getBuycontent())) {
            tvAttation.setText(details.getBuycontent());
        }else
            tvAttation.setText("暂无内容");
        //判断关注标记	0未关注；1已关注
        String follow = details.getFollowflag();
        if (follow == null || follow.equals("0")) {
            titleRightImg.setImageResource(R.drawable.heart_while_stroke);
        } else {
            titleRightImg.setImageResource(R.drawable.heart_while);
        }
        //价值图文详情
//		String sys_web_plugins = BaseApplication.getInstance().getSysInitInfo().getSys_web_service();
//		String path = sys_web_plugins + "webview/parm/blogdetail_"+details.getId();
//		webview.loadUrl(path);
    }

    /**
     * 将用户详情里的role转换为获取商品详情的role
     *
     * @param role
     * @return
     */
    private void transRole(String role) {
        if (role.equals("1")) {//田家用户
            keytype = "3";
            keyid = client_id;
        } else if (role.equals("2")) {//地标商家
            keytype = "4";
            keyid = "无";
        } else if (role.equals("3")) {//村游商家
            keytype = "5";
            keyid = "无";
        } else if (role.equals("6")) {//乐乐商家
            keytype = "9";
            keyid = "无";
        } else if (role.equals("7")) {//特产商家
            keytype = "11";
            keyid = "无";
        } else if (role.equals("8")) {//粮库商家
            keytype = "16";
            keyid = "0";
        } else if (role.equals("11") || role.equals("12")) {//走走商家
            keytype = "10";
            keyid = "75";
        } else if (role.equals("21")) {//苗木
            keytype = "12";
            keyid = "无";
        } else if (role.equals("22")) {//花卉
            keytype = "13";
            keyid = "无";
        } else if (role.equals("23")) {//家电
            keytype = "14";
            keyid = "无";
        } else if (role.equals("24")) {//日用商品
            keytype = "15";
            keyid = "无";
        } else if (role.equals("31")) {//31农需商家
            keytype = "17";
            keyid = "无";
        }
    }

    @OnClick({R.id.title_left_btn, R.id.title_right_img, R.id.img_merchant, R.id.tv_phone, R.id.tv_consult_online, R.id.tv_merchant_address, R.id.layout_all_production, R.id.layout_introduce, R.id.iv_info, R.id.ll_return_top})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_img:
                loginCallBack = new LoginUtil.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        String token = getApplicationContext().getUser().getToken();
                        if ("0".equals(details.getFollowflag())) {//未关注
                            getNetWorker().FolColOperate(token, "1", "1", details.getId());
                        } else {//已关注
                            getNetWorker().FolColOperate(token, "1", "2", details.getId());
                        }
                        loginCallBack = null;
                    }
                };
                LoginUtil.getInstance(mContext, loginCallBack);
                break;
            case R.id.img_merchant:
                if (details == null)
                    break;
                Intent itLarge = new Intent(mContext, ShowLargeImageActivity.class);
                String imgurl_detail = details.getBackimg();
                ArrayList<Img> imgs = new ArrayList<Img>();
                Img img = new Img(imgurl_detail);
                imgs.add(img);
                itLarge.putExtra("imgs", imgs);//所有的图片地址
                itLarge.putExtra("position", 1);//当前是第几张图片
                startActivity(itLarge);
                break;
            case R.id.tv_phone:
                if (details == null)
                    break;
                final String phone = details.getMobile();
                if (phone != null && !phone.isEmpty() && !phone.equals("无")) {
                    HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
                    hbDialog.setText("是否直接拨打" + phone + "?");
                    hbDialog.setLeftButtonText("取消");
                    hbDialog.setRightButtonText("拨打");
                    hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
                    hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                        @Override
                        public void onLeftButtonClick(HemaButtonDialog dialog) {
                            dialog.cancel();
                        }

                        @Override
                        public void onRightButtonClick(HemaButtonDialog dialog) {
                            dialog.cancel();
                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(
                                    "tel:" + phone));
                            startActivity(intent);
                        }
                    });
                } else {
                    showTextDialog("对方没有提供有效的电话号码");
                }
                break;
            case R.id.tv_consult_online:
                if (details == null)
                    break;
                String mQQNum = details.getQq();
                if (mQQNum == null || mQQNum.isEmpty() || mQQNum.equals("null")) {
                    XtomToastUtil.showShortToast(mContext, "对方没有指定QQ");
                    break;
                }
                String url = "mqqwpa://im/chat?chat_type=wpa&uin=" + mQQNum;
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                } catch (Exception e) {
                    showTextDialog("打开QQ客户端失败\n请确保已经安装了QQ手机客户端");
                    e.printStackTrace();
                }
                break;
            case R.id.tv_merchant_address:
                Intent itAddress = new Intent(mContext, SellerMapActivity.class);
                itAddress.putExtra("merchant", details);
                startActivity(itAddress);
                break;
            case R.id.layout_all_production:
                lineIntroduce.setVisibility(View.GONE);
                lineProducts.setVisibility(View.VISIBLE);
                layoutInfo.setVisibility(View.GONE);
                listview.setVisibility(View.VISIBLE);
                break;
            case R.id.layout_introduce:
                lineIntroduce.setVisibility(View.VISIBLE);
                lineProducts.setVisibility(View.GONE);
                layoutInfo.setVisibility(View.VISIBLE);
                listview.setVisibility(View.GONE);
                break;
            case R.id.iv_info:
                ArrayList<Img> imgs2 = new ArrayList<Img>();
                Img img2 = new Img(details.getImgurl0());
                imgs2.add(img2);

                Intent intent = new Intent();
                intent.setClass(mContext, ShowLargeImageActivity.class);
                intent.putExtra("imgs", imgs2);
                intent.putExtra("position", 1);
                mContext.startActivity(intent);
                break;
            case R.id.ll_return_top:
                scrollview.smoothScrollTo(0, 0);
                break;
        }
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            if (loginCallBack != null)
                loginCallBack.onLogin();
        }
    }
}
